import  pandas as pd
import  json
import tos
import  time
import uuid
import  random
import mysql.connector
import logging
from bytehouse_driver import Client
import numpy as np

# Access key 和 Secret key 可在用户火山引擎账号中查找
ak = "AKLTMmFmMzVmNmY5ZDEyNDNmNWEyZTU2MDM3Y2EzMDJlZTk"
sk = "WVdNeFpXRXdNekV4Tm1ZME5EZGxPRGc0TUdFNE1HWXdNV1ZqTkdNNU9HRQ=="
# your endpoint 和 your region 填写Bucket 所在区域对应的Endpoint。# 以华北2(北京)为例，your endpoint 填写 tos-cn-beijing.volces.com，your region 填写 cn-beijing。
endpoint = "tos-cn-beijing.ivolces.com"
region = "cn-beijing"

def get_dict(vechicle_id,start_time_str,bagid,path,scid_dict,level1,level2,level3):
    dict = {}
    dict["vehicle_id"] = vechicle_id
    dict["start_time_str"] = start_time_str
    dict["scid"] = bagid
    dict["path"] = path
    dict["level1"] = level1
    dict["level2"] = level2
    dict["level3"] = level3
    day = start_time_str[0:4] + start_time_str[5:7] + start_time_str[8:10]
    month = start_time_str[0:4] + start_time_str[5:7]
    dict["day"] = day
    dict["month"] = month
    dict["scid_start_time_str"] = scid_dict["scid_start_time_str"]
    dict["icu2_odometer"] = scid_dict["ICU2_Odometer"]
    dict["idb3_vehiclespd"] = scid_dict["IDB3_VehicleSpd"]
    dict["acu2_longaccsensorvalue"] = scid_dict["ACU2_LongAccSensorValue"]
    dict["acu2_lataccsensorvalue"] = scid_dict["ACU2_LatAccSensorValue"]
    dict["acu2_vehicledynyawrate"] = scid_dict["ACU2_VehicleDynYawRate"]
    dict["eps1_steeranglespd"] = scid_dict["EPS1_SteerAngleSpd"]
    dict["lane_curvature"] = scid_dict["lane_curvature"]
    dict["eps1_torsionbartorque"] = scid_dict["EPS1_TorsionBarTorque"]
    dict["cs1_gearpositionreqst"] = scid_dict["CS1_GearPositionReqSt"]
    dict["lane_curvature"] = scid_dict["lane_curvature"]

    uid_string = vechicle_id + start_time_str + bagid + level1 + level2 + level3
    uid = str(uuid.uuid3(uuid.NAMESPACE_DNS, uid_string))
    dict["uid"] = uid
    return dict
def get_dict_list(dict):
    data_list=[]
    data_list.append(dict['vehicle_id'])
    data_list.append(dict['start_time_str'])
    data_list.append(dict['scid'])
    data_list.append(dict['path'])
    data_list.append(dict['level1'])
    data_list.append(dict['level2'])
    data_list.append(dict['level3'])
    data_list.append(dict['day'])
    data_list.append(dict['month'])
    data_list.append(dict["scid_start_time_str"])
    data_list.append(dict['icu2_odometer'])
    data_list.append(dict['idb3_vehiclespd'])
    data_list.append(dict['acu2_longaccsensorvalue'])
    data_list.append(dict['acu2_lataccsensorvalue'])
    data_list.append(dict['acu2_vehicledynyawrate'])
    data_list.append(dict['eps1_steeranglespd'])
    data_list.append(dict['lane_curvature'])
    data_list.append(dict['eps1_torsionbartorque'])
    data_list.append(dict['cs1_gearpositionreqst'])
    data_list.append(dict['uid'])
    data_list.append(dict['day'])
    return data_list
def add_to_bytehouse_dict(dict):
    HOST="bytehouse-cn-beijing.volces.com"
    PORT="19000"
    API_KEY="q2p9nLj7tq:TKOCmgrMKp"
    # 配置数据库连接信息
    DATABASE="dwd"
    client = Client.from_url('bytehouse://{}:{}/?user=bytehouse&password={}&database={}&secure=true'.format(HOST, PORT, API_KEY, DATABASE))
    client.execute("INSERT INTO ods.ods_trigger_sc  VALUES", [
        [dict['vehicle_id'], dict['scid'], dict['start_time'], dict['path'], dict['plat'], dict['project'],dict['day'],dict['isdelete']
            , dict['pt_date'], dict['pt_hour'],dict['pt_vehicleseries'],dict['pt_plat']
        ]])
    return
def get_aeb_scid_time(df_can_100ms_save_path, vehicle_id, bagid, daystr, hourstr):
    try:
        df_can_100ms_aeb= pd.read_pickle(df_can_100ms_save_path)
    except Exception as e:
        print('data report read error, ', str(e))

    df_aeb_100ms_list = df_can_100ms_aeb[
        ['start_time_str', 'path', 'nsecs', 'VLCCDHypotheses_Hypothesis_0_fTTC', 'VLCCDHypotheses_Hypothesis_0_fDistX',
         'VLCCDHypotheses_Hypothesis_0_fDistY',
         'VLCCDHypotheses_Hypothesis_0_fVrelX', 'VLCCDHypotheses_Hypothesis_0_fVrelY', 'IDB3_VehicleSpd',
         'ACU2_LongAccSensorValue', 'ACU2_LatAccSensorValue',
         'ACU2_VehicleDynYawRate', 'IDB1_BrakePedalApplied', 'EPS1_SteerAngleSpd',
         'CamLaneData_CourseInfo_1_CourseInfoSegNear_f_C0',
         'ADCS2_AEBPartialBrake', 'ADCS2_AEBFullBrake','ICU2_Odometer','EPS1_TorsionBarTorque','CS1_GearPositionReqSt'
         ]].values.tolist()
    found_index = -9999
    found_start_time_str=""
    found_path=""
    # 遍历列表

    for index, element in enumerate(df_aeb_100ms_list):
        start_time_str=element[0]
        path = element[1]
        nsecs = element[2]
        ADCS2_AEBPartialBrake = element[15]
        ADCS2_AEBFullBrake = element[16]
        if (ADCS2_AEBPartialBrake==1 or ADCS2_AEBFullBrake==1):
            found_index = index
            found_path=path
            found_start_time_str=start_time_str

            break  # 找到第一个符合条件的元素就跳出循环
    logging.info("found_index: "+str(found_index))
    if found_index==  -9999:
        dict_scid = {}
        dict_scid["vehicle_id"] = vehicle_id
        dict_scid["scid"] = bagid
        dict_scid["start_time"] =""
        dict_scid["path"] = df_aeb_100ms_list[0][1]
        dict_scid["plat"] = "TDA4"
        dict_scid["project"] = "EP36"
        dict_scid["day"] = daystr
        isdelete = random.randint(0, 9)
        dict_scid["isdelete"] = isdelete
        dict_scid["pt_date"] = daystr
        dict_scid["pt_hour"] = hourstr
        dict_scid["pt_vehicleseries"] = 'EP36'
        dict_scid["pt_plat"] = 'TDA4'
        add_to_bytehouse_dict(dict_scid)
    else:
        dict_scid = {}
        dict_scid["vehicle_id"] = vehicle_id
        dict_scid["scid"] = bagid
        dict_scid["start_time"] = found_start_time_str
        dict_scid["path"] = found_path
        dict_scid["plat"] = "TDA4"
        dict_scid["project"] = "EP36"
        dict_scid["day"] = daystr
        isdelete = random.randint(0, 9)
        dict_scid["isdelete"] = isdelete
        dict_scid["pt_date"] = daystr
        dict_scid["pt_hour"] = hourstr
        dict_scid["pt_vehicleseries"] = 'EP36'
        dict_scid["pt_plat"] = 'TDA4'
        add_to_bytehouse_dict(dict_scid)
